<?php

/*
 +-------------------------------------------------------------------+
 |                          user.php                                 |
 |                                                                   |
 | Copyright ?                          www.gde.sclab.clarkson.edu   |
 | Author: Demetrios Dimatos            www.dimatos.net              |
 | Created: August 2006                 Last modified: Oct 15, 2006  |
 +-------------------------------------------------------------------+
 | These functions are used to aid in validating,registering,        |
 | updating last seen, converting id's,etc.                          |
 |  - /gde-1.0/includes/public/login.ctl.php                         |
 |  - /gde-1.0/templates/public/login.php                            |
 +-------------------------------------------------------------------+
*/

 // Include configuration variables
 include_once('/var/www/gde-1.0/htdocs/config.php');
 // Include templating for paging html 
 include_once(Config::base_path.Config::adodb_path.'adodb-pager.inc.php');
 // Include templating for exceptions 
 include_once(Config::base_path.Config::adodb_path.'adodb-exceptions.inc.php');
  // Include templating for html 
 include_once(Config::base_path.Config::html_func_path ."html.php");

 
class User
{
	private $userId;
	private $userName;
	private $password;
	private $emailAddress;
	private $lastLogin;
	private $database_connection;
	
	var $result;
	
  /**
   * Default constructor for user class. Sets $userId,$userName,$password,$emailAddress
   * $lastLogin,$database_connection all to null
   *
   * @return User
   */
  function User()
  {
  	 $userId = null;
  	 $userName = null;
  	 $password = null;
  	 $emailAddress = null;
  	 $lastLogin = null;
  	 $database_connection = null;
  }
  
 	/**
 	 * Check if user is a valid user.
 	 *
 	 * @param string $username - username for database connecion
 	 * @param string $password - password for username to database
 	 * @param adodb connection $database_connection - adodb connection from a database
 	 * @return string empty - user did not fill in form || badusername - user enters || badpassword - user enters invalid password || valid - user has entered valid password and username 
 	 * @author Demetrios Dimatos
 	 */
	function Authenticate($username,$password,$database_connection)
  {
  	if(!$username || !$password)
  	{
  		return "empty";
  	}
  	
		try
		{
			$sql = 'select * from forum_users where username="'.addslashes($username).'" and password="'.addslashes(md5($password)).'" limit 1';
    	$this->result = $database_connection->Execute($sql);
		}
		catch (Exception $e)
		{
			// This will execute in the case where the sql is wrong.
			die( "ERROR executing query for user"." $username <br> ".$e->getMessage());
		}
		
		if($this->result->RecordCount() == 0)
		{
			try 
			{
				$sql = 'select * from forum_users where username="'.addslashes($username).'" limit 1';
				$this->result = $database_connection->Execute($sql);
			}
			catch (Exception $e)
			{
				die( "ERROR executing query for user"." $username <br> ".$e->getMessage());
			}
			
			if($this->result->RecordCount() == 0)
			{
				//echo "\n[ You have entered an invalid user name ]\n";
				return "badusername";
			}
			
			try 
			{
				$sql = 'select * from forum_users where password="'.addslashes(md5($password)).'" limit 1';
				$this->result = $database_connection->Execute($sql);
			}
			catch (Exception $e)
			{
				die( "ERROR executing query for user"." $username <br> ".$e->getMessage());
			}
			
			if($this->result->RecordCount() == 0)
			{
				//echo "\n[ You have entered an invalid password ]\n";
				return "badpassword";
			}
		}
		return "valid";
  }

  /**
   * Inserts the date the user was last seen
   *
   * @param string $username - GDE logged/valid user
   * @param adodb connection $database_connection - adodb connection to a database
   * @return string true/false - for success if user is updated
   * @author Demetrios Dimatos
   */
	function UserUpdateLastseen($username,$database_connection)
  {
   	try 
   	{ 
   		$sql='update forum_users set lastseen=NOW() where user_id="'.addslashes($username).'"';
   		$this->result = $database_connection->Execute($sql); 
   	}
   	catch (Exception $e) 
   	{ 
   		die( "ERROR executing query for user"." $username <br> ".$e->getMessage());
   	}
   	//if (!$this->result) mylogerr($database_connection->ErrorMsg());
   	return $this->result = true;
  }
  
  /**
   * Convert username to user id
   *
   * @param string $username
   * @param adodb connection $database_connection - adodb connection to a database
   * @return adodb resultset object - user id
   * @author Demetrios Dimatos
   */
  function UsernameToId($username,$database_connection)
  {
  	try 
   	{ 
   		$sql='select user_id from forum_users where username="'.addslashes($username).'" limit 1';
   		$this->result = $database_connection->Execute($sql); 
   	}
   	catch (Exception $e) 
   	{ 
   		die('Could not get userid.'); 
   	}
   	
   	if($this->result->RecordCount() == 0)
		{
			die('Could not get userid.'); 
		}
   	return $this->result;
  }

    /**
   * Convert user id to username 
   *
   * @param string $username
   * @param adodb connection $database_connection - adodb connection to a database
   * @return adodb resultset object - user name
   * @author Demetrios Dimatos
   */
  function IdToUsername($userId,$database_connection)
  {
  	try 
   	{ 
   		$sql='select username from forum_users where user_id="'.addslashes($userId).'" limit 1';
   		$this->result = $database_connection->Execute($sql); 
   	}
   	catch (Exception $e) 
   	{ 
   		die('Could not get username.'); 
   	}
   	
   	if($this->result->RecordCount() == 0)
		{
			die('Could not get username.'); 
		}
   	return $this->result;
  }
  
  /**
   * Adds a new user to GDE
   *
   * @param string $firstname - users fist name
   * @param string $lastname - users last name
   * @param string $username - desired username
   * @param string $password - password
   * @param string $retype_passwd - retyped password
   * @param string $email - users email
   * @param adodb connection $database_connection - adodb connection to a database
   * @return string empty - when one of the fields is not filled out || missmatch	- passwords did not match || duplicate	- insert fails on duplicate key usernames || valid	- when user is registered successfully ||valid	- when user is registered successfully 
   * @author Demetrios Dimatos
   */
  function RegisterUser($firstname, $lastname, $username, $password, $retype_passwd, $email, $database_connection)
  {
  	if( !$firstname  || !$lastname || !$username || !$password || !$retype_passwd || !$email)
  	{
  		echo "$firstname $lastname $username $password $email $retype_passwd";
  	  return "empty";
  	}
  	
  	if($password != $retype_passwd)
  	{
  		return "missmatch";
  	}
  	
  	try 
   	{ 
   		$sql= 'insert into forum_users values (NULL,NOW(),"'.addslashes($username).'","'.addslashes(md5($password)).'",NOW(),1,10000)';
   		$this->result = $database_connection->Execute($sql); 
   		
   		try 
   		{
      // Ideally here we should search a table of usersinfo, find a col of grant levels, and assign on this over *.*
		  $sql_grant = 'grant all on *.* to '.$username.'@'.Config::db_host.' identified by \''.$password.'\'';
		  $database_connection->Execute($sql_grant);
   		}
   		catch (Exception $e)
   		{
   		  echo "Failed to Grant permissions!";
   		  var_dump($e);
		    adodb_backtrace($e->getTrace());
   		}
   	}
   	catch (Exception $e) 
   	{ 
   		//Case where the user already exists, no duplicates so send them back to register.php
   		//message2redirect("That username has already been chosen. Please Try Another.",Config::url_public."register.php",5);
   		//return $this->result = false;
   		return "duplicate";
   	}   
   	//Case where user success on registering so send it index page.
    //message2redirect("",Config::url_public."index.php",5);
    //return $this->result = true;
    return "valid";
  }
}		

?>